<template>
    <div class="chatWindow">
        <div class="chat"
             style="width:100%;height:65px;border-bottom: 2px solid #f7f7f7;display: flex;align-items: center">
            <!--left-->
            <div class="chatBG">
                <div class="chatTop font">
                    <div class="userName">{{communication.talent.name}}</div>
                    <el-popover placement="bottom-start"
                                :width="$pop.licenseWidth"
                                trigger="hover"
                                :disabled="$pop.getLicensesString(communication.talent.license).all.length===0">
                        <p v-for="(lt,li) in $pop.getLicensesString(communication.talent.license).all" :key="li">
                            {{lt}}</p>
                        <div slot="reference">{{$pop.getLicensesString(communication.talent.license).first}}</div>
                    </el-popover>
                    <div style="margin-left: 10px;">
                        {{communication.talent.salary}}
                    </div>
                </div>
                <div class="chatBox ltext">
                    <div>{{communication.talent.city}}</div>
                    <div style="margin-left: 15px;margin-right: 15px;">|</div>
                    <div>{{communication.talent.age}}</div>
                    <div style="margin-left: 15px;margin-right: 15px;">|</div>
                    <div>{{communication.talent.workTime}}</div>
                    <div style="margin-left: 15px;margin-right: 15px;">|</div>
                    <div>{{communication.talent.education}}</div>
                </div>
            </div>
            <!--right-->
            <div class="chatR">
                <span>沟通职位：</span>
                <span class="fontColor">{{communication.job.name}}</span>
            </div>
        </div>
        <el-scrollbar ref="myScrollbar" style="width:100%;height: calc(100% - 205px);">
            <div class="record_list_cls">
                <record-item v-for="(t,i) in recordsCache" :key="i"
                             :record="t"></record-item>
            </div>
        </el-scrollbar>
        <!--消息提醒-->
        <div v-if="communication.haveNewQ" class="new_message_cls">
            <p class="new_message_text">收到入职邀请</p>
            <el-button class="new_message_detail">查看详情
            </el-button>
        </div>
        <!--right-buttom内容-->
        <div class="chatBottom">
            <div class="comContBG fonSize font9 fR Rb">
                <div v-show="showInvited" class="comContBG curso" @click="doInduction">
                    <div :class="{'icon_green':!invitedQ,'icon_gray':!invitedQ}" class="icon_margin"></div>
                    <div :class="{'fontG':!invitedQ,'font9':invitedQ}">{{!invitedQ?'邀请入职':'已邀请'}}</div>
                </div>
                <div v-show="showFit" class="comContBG curso" @click="diFit">
                    <div class="icon_margin"
                         :class="{'icon_fit_black':fitQ,'icon_fit_red':!fitQ}"></div>
                    <div :class="{'font9':fitQ,'fontR':!fitQ}">
                        不合适
                    </div>
                </div>
            </div>
            <textarea @keyup.enter.exact="clickSend" @keyup.ctrl.enter.exact="addNewLine" maxlength="200"
                      class="input_text_cls" placeholder="输入文字，最多200字"
                      v-model="currentInput">

            </textarea>

            <div style="font-size:12px;color:#999;position:absolute;bottom: 15px;right: 125px;">按Ctrl+Enter换行，Enter发送
            </div>
            <el-button class="btn font9" @click="clickSend">发送</el-button>
        </div>
    </div>
</template>

<script>
  import _subject from '../../../assets/utils/subject'
  import RecordItem from './RecordItem'
  import _g from '../../../assets/utils/global'
  import * as _ from 'underscore'
  import comm from '../../../assets/utils/comm'

  export default {
    name: 'chatWindow',
    components: { RecordItem },
    props: {
      side: {
        type: String,
        default: 'company'
      },
      commId: {
        type: Number,
        default: 0
      },
      toId: {
        type: Number,
        default: 0
      },
      jrrId: {
        type: Number,
        default: 0
      },
      createTime: {
        type: Number,
        default: 0
      },
      commInfo: {
        type: Object,
        default: {}
      },
      fitQ: {
        type: Boolean,
        default: false
      },
      invitedQ: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      commId: {
        immediate: true,
        handler() {
          if (this.commId) {
            //重新开始分页
            this.page.current = 0
            this.communication.records.splice(0, this.communication.records.length)
            this.loadRecords()
          }
        }
      },
      commInfo: {
        immediate: true,
        handler(n) {
          if (n) {
            this.communication.job.name = n.jobName
            if (n.talent && n.talent.talent) {
              const base = n.talent.talent
              this.communication.talent.name = base.talentName
              this.communication.talent.salary = (base.tax === 0 ? '税前' : '税后') + base.salaryPerMonth + 'W/' + base.monthCount + '年'
              this.communication.talent.license = n.talent.licenseList
              this.communication.talent.city = base.workCity
              this.communication.talent.age = base.talentAge + '岁'
              this.communication.talent.workTime = base.workDay + '年'
              this.communication.talent.education = n.talent.educationList.length ?
                _.map(
                  n.talent.educationList,
                  t => {
                    return t.academicStr
                  }
                ).join(',') : '学历未知'
            }
          }
        }
      }
    },
    computed: {
      showInvited() {
        if (this.fitQ) {
          return false
        } else {
          return !this.invitedQ
        }
      },
      showFit() {
        return !this.fitQ
      },
      recordsCache() {
        //是否显示时间
        for (let i = 1; i < this.communication.records.length; i++) {
          const last = this.communication.records[i - 1]
          const current = this.communication.records[i]
          current.showTimeQ = current.time - last.time > 3 * 60 * 1000
        }
        _.each(this.communication.records, t => {
          t.icon = t.meQ ? _subject.getCompanyIcon() : comm.toIcon
        })
        return this.communication.records
      }
    },
    data() {
      return {
        currentInput: '',
        wsSub: null,
        page: {
          current: 0,
          size: 10,
          total: 0,
          lastHeight: 0//加载新页之前scrollbar的高度
        },
        communication: {
          haveNewQ: false,
          //开始沟通时间
          startTime: '2019-5-15 12:00:00',
          //人才信息
          talent: {
            name: '高女士',
            image: '头像',
            license: '执业类型',
            salary: '期望年薪',
            city: '所在城市',
            age: '年龄',
            workTime: '工作年限',
            education: '学历'
          },
          //职位信息
          job: {
            name: '职位名称',
            //沟通状态，0未邀请，1已邀请，2不合适
            commState: '是否邀请'
          },
          //沟通的阶段
          state: 0,
          //沟通记录
          records: []
        }
      }
    },
    methods: {
      getNewMessage(commId, unread) {
        this.$emit('new-msg', commId, unread)
      },
      onScrollTop() {
        this.loadRecords()
      },
      scrollDown() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      scrollPercent() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight - this.page.lastHeight
          this.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      diFit() {
        _g.apiPost('/company/updateAppropriate.do', { relationshipId: this.jrrId, state: 2, value: 4 })
          .then(res => {
            if (res && res.status === 0) {
              this.$emit('comm-ops', this.commId, 'fit')
              this.sendNotFit()
            } else {
              _g.toMessage(res, null)
            }
          })
      },
      doInduction() {
        _g.apiPost('/company/invitationInduction.do', { jrrId: this.jrrId, state: 1 })
          .then(res => {
            if (res && res.status === 0) {
              this.$emit('comm-ops', this.commId, 'invite')
              this.sendInvitation()
            } else {
              _g.toMessage(res, null)
            }
          })
      },
      sendNotFit() {
        this.sendContent('已将对方简历标记为不合适', 1)
      },
      sendInvitation() {
        this.sendContent('入职邀请已发送给对方', 2)
      },
      sendContent(text, type) {
        const str = {
          'toCom': 'talent',
          'toUserId': String(this.toId),
          'comid': String(this.commId),
          'type': 'SINGLE_SENDING',
          'content': text,
          'mainUserId': _subject.getCompanyId(),
          'mainCom': 'company',
          'send_state': String(type)
        }
        _subject.ws.next(str)
        //添加到本地记录
        if (type === 2) {
          if (this.side === 'company') {
            type = 1
          } else {
            type = 2
          }
        }
        let content = this.getSysMsg(type, text)
        this.communication.records.push({
          type: type,
          content: content,
          meQ: true,
          time: new Date().format('yyyy-MM-dd hh:mm:ss')
        })
        this.scrollDown()
      },
      addNewLine() {
        this.currentInput += '\n'
      },
      clickSend() {
        //防止多个换行的情况
        let trim = this.currentInput.trim()
        if (trim) {
          this.sendContent(trim.replace(/\n/g, '<br/>'), 0)
          this.currentInput = ''
        }
      },
      getSysMsg(type, text) {
        if (type === 1) {
          switch (text) {
            case '拒绝':
              return '人才已拒绝您的入职邀请'
            case '接受':
              return '人才已接受您的入职邀请'
          }
        }
        return text
      },
      loadRecords() {
        _g.apiPost('/company/selectComDetailInfo.do', {
          comID: this.commId,
          currPageNo: this.page.current + 1,
          pageSize: this.page.size
        }).then(res => {
          if (res && res.status === 0) {
            const page = res.data.pageInfo
            this.page.total = page.total
            this.page.current = page.pageNum
            if (page.list.length > 0) {
              let temp = _.map(page.list, t => {
                const o = JSON.parse(t.content)
                const state = Number(o.send_state)
                let type = state
                let content = this.getSysMsg(state, o.content)
                if (state === 2 && this.side === 'company') {
                  type = 1
                }
                const time = Date.parse(t.time)
                return {
                  image: o.head,
                  showTimeQ: false,
                  meQ: o.mainCom === this.side,
                  content: content,
                  type: type,
                  time: time
                }
              })
              temp = _.sortBy(temp, t => {
                return t.time
              })
              if (this.page.current === 1) {
                this.communication.records = temp
                this.scrollDown()
              } else {
                this.communication.records = temp.concat(this.communication.records)
                this.scrollPercent()
              }
            } else {
              this.page.current -= 1
            }
          }
        })
      }
    },
    created() {
      let self = this
      this.wsSub = _subject.ws.subscribe({
        next(t) {
          console.log('ws new message', t)
          if (t.status === 200) {
            let m = t.data.type
            if (m === 'SINGLE_SENDING') {
              let commId = t.data.comid
              let mainId = t.data.mainUserId
              let toId = t.data.toUserId//对方发送的消息
              //通知收到父组件消息
              self.getNewMessage(Number(t.data.comid), Number(t.data.unread))
              console.log('reach chat window before', commId, mainId, toId, self.commId, _subject.getCompanyId(), self.toId)
              if (commId === String(self.commId) && toId === String(_subject.getCompanyId()) && mainId === String(self.toId)) {
                console.log('reach chat window after', commId, mainId, toId, self.commId, _subject.getCompanyId(), self.toId)
                const type = Number(t.data.send_state)
                const content = self.getSysMsg(type, t.data.content)
                self.communication.records.push({
                  type: type,
                  content: content,
                  meQ: false,
                  time: new Date().format('yyyy-MM-dd hh:mm:ss')
                })
              }
              self.scrollDown()
            }
          } else if (t.status === -1) {
            _g.message('对方不在线，可能无法立即回复您', 'warning')
          }
        }
      })
    },
    destroyed() {
      if (this.wsSub) {
        this.wsSub.unsubscribe()
      }
    },
    mounted() {
      this.$refs['myScrollbar'].wrap.onscroll = e => {
        if (e.target.scrollTop === 0) {
          this.onScrollTop()
        }
      }
    }
  }
</script>

<style lang="scss" scoped>

    .chatWindow {
        height: 100%;
        width: 100%;
        position: relative;
        /*border: 2px solid red;*/
    }

    .communiBg {
        width: 1200px;
        margin: 0 auto;
        padding-top: 20px;
        display: flex;
        flex-direction: row;
    }

    .chat {
        display: flex;
        flex-direction: row;
        font-size: 13px;
        position: relative;

        width: 100%;

        /*border: red solid 1px;*/
    }

    .chatTop {
        display: flex;
        flex-direction: row;
        align-items: flex-end;
        font-size: 13px;
        position: relative;

        width: 100%;

        /*border: red solid 1px;*/
    }

    .chatBox {
        width: fit-content;
        height: 20px;
        /*border: 1px solid #F7F7F7;*/
        display: flex;
        flex-direction: row;
        font-size: 13px;
    }

    .userName {
        font-size: 17px;
    }

    .font {
        font-weight: bold;
        margin-top: 5px;
        margin-bottom: 5px;
    }

    .font > div {
        margin-left: 10px;
        margin-right: 10px;
        margin-top: 5px;
    }

    .font > div:nth-child(1) {
        margin-left: 0px;
        margin-top: 0px;
    }

    .chatBG {
        margin-left: 50px;
    }

    .chatR {
        position: absolute;
        right: 50px;
    }

    .fontColor {
        color: #4AB0CF;
    }

    .font9 {
        color: #999;
    }

    .fonSize {
        font-size: 14px;
    }

    .fonP {
        width: 118px;
        height: 11px;
        /*background-color: #4ab0cf;*/
        position: absolute;
        top: 95px;
        left: 43%;
    }

    .empty {
        width: 300px;
        height: 1px;
        background-color: #F7F7F7;
    }

    .rightB {
        position: absolute;
        top: 900px;
    }

    .chatBottom {

        width: 100%;
        height: 140px;
        border-top: 2px solid #f7f7f7;
        position: absolute;
        bottom: 0;

        padding: 0;

        .input_text_cls {
            resize: none;

            width: calc(100% - 65px);
            height: calc(100% - 70px);

            display: block;

            padding: 0;

            margin-top: 5px;
            margin-left: 15px;

            font-size: 13px;

            border: none;

        }
    }

    .Rb {
        margin-right: 50px;
        margin-top: 5px;
    }

    .Rb > div:nth-child(1) {
        margin-right: 30px;
    }

    .fontG {
        color: #009944;
        font-size: 13px;
    }

    .fontR {
        color: #dd3a31;
        font-size: 13px;
    }

    .btn {
        width: 72px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        border: 1px solid #CCCCCC;
        border-radius: 18px;
        color: #CCCCCC;
        position: absolute;
        right: 40px;
        bottom: 10px;
        cursor: default;
        padding: 0;
        font-size: 14px;
    }

    .curso {
        cursor: default;
    }

    .text1 {
        color: #333;
        margin-top: 53px;
        margin-left: 50px;
        text-align: left;
    }

    .icon_margin {
        margin-right: 5px;
        margin-top: 2px;
    }

    .icon_green {
        width: 12px;
        height: 12px;
        background: url("../../../assets/img/communication/invitation_green.jpg") no-repeat;
        background-size: cover;
    }

    .icon_gray {
        width: 12px;
        height: 12px;
        background: url("../../../assets/img/communication/invitation_gray.png") no-repeat;
        background-size: cover;
    }

    .icon_fit_black {
        width: 12px;
        height: 12px;
        background: url("../../../assets/img/communication/fit_black.jpg") no-repeat;
        background-size: cover;
    }

    .icon_fit_red {
        width: 12px;
        height: 12px;
        background: url("../../../assets/img/communication/fit_red.png") no-repeat;
        background-size: cover;
    }

    .msg, .inap {
        width: 228px;
        height: 33px;
        line-height: 33px;
        text-align: center;
        background-color: #f7f7f7;
        border-radius: 17px;
        font-size: 14px;
        color: #333;
        position: absolute;
        top: 115px;
        left: 36%;
    }

    .inap {
        position: absolute;
        top: 40px;
        left: 36%;
    }

    .fT {
        position: absolute;
        top: 92px;
        left: 46%;
    }

    .toux {
        width: 24px;
        height: 24px;
        border: 1px solid #F7F7F7;
        border-radius: 25px;
        overflow: hidden;
        position: absolute;
        right: 50px;
        top: 32px;

        img {
            width: 100%;
        }
    }

    .textDiv {
        width: 294px;
        height: 53px;
        background-color: #F7F7F7;
        border-radius: 10px;
        line-height: 53px;
        text-align: center;
        color: #333;
        position: absolute;
        right: 84px;
        top: 32px;
    }

    .marginT {
        margin-top: 35px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-around;

        width: 100%;

        /*border: red solid 1px;*/
    }

    .content {
        height: 732px;
        position: relative;
    }

    .comContBG {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
    }

    .entry {
        position: relative;
    }

    .entryfont {
        position: absolute;
        top: 170px;
        left: 45%;
    }

    .start_time_cls {
        font-size: 14px;
        font-weight: 400;
        color: rgba(153, 153, 153, 1);
    }

    .record_list_cls {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-start;

        padding-left: 10px;
        padding-right: 10px;
    }

    .new_message_cls {

        display: flex;
        align-items: center;

        width: 100%;
        height: 50px;
        background: rgba(240, 169, 98, 1);

        position: absolute;
        left: 0;
        bottom: 182px;
    }

    .new_message_text {
        font-size: 14px;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);

        position: absolute;
        left: 49px;

    }

    .new_message_detail {

        background: transparent;

        width: 96px;
        height: 30px;
        border: 1px solid rgba(255, 255, 255, 1);
        border-radius: 15px;

        font-size: 14px;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);

        position: absolute;
        right: 50px;
    }

    .new_message_cls > button {
        padding: 0;
    }

</style>
